package com.zjitc.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjitc.common.ServerResponse;
import com.zjitc.model.Product;
import com.zjitc.service.ProductService;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/26 15:12
 * @description:
 */
@Controller
@RequestMapping("/product")
public class ProductController {

  @Autowired
  private ProductService productService;

  /**
   * 查询所有商品,并实现分页
   * @param type
   * @param session
   * @return
   */
  @RequestMapping("/productAll")
  public String productAll(
      @RequestParam(name = "pageNum", required = true, defaultValue = "1") Integer page,
      @RequestParam(name = "type", required = true, defaultValue = "1") String type,HttpSession session
  ) {
    PageHelper.startPage(page, 8);
    List<Product> list = productService.productAll(type);
    PageInfo<Product> pageInfo = new PageInfo<>(list);
    System.out.println(pageInfo);
    session.setAttribute("type",type);
    session.setAttribute("page", pageInfo);
    session.setAttribute("product",list);
    return "product";
  }

  /**
   * 添加商品
   * @return
   */
  @RequestMapping("/addProduct")
  public String addProduct(){
    return "control";
  }

  /**
   * 添加商品
   * @param product
   * @param session
   * @return
   */
  @RequestMapping("/pushProduct")
  public String pushProduct(Product product, HttpSession session){
    ServerResponse<Product> response = productService.pushProduct(product);
    if (response.getStatus()==1){
      session.setAttribute("pushProduct","添加商品失败");
      return "control";
    }else {
      session.removeAttribute("返回注册信息");
      return "main";
    }
  }

  /**
   * 显示商品信息
   * @param pid
   * @param session
   * @return
   */
  @RequestMapping("/showProduct")
  public String showProduct(Integer pid, HttpSession session){
    Product product = productService.showProduct(pid);
    session.setAttribute("showProduct",product);
    return "product_detail";
  }

}
